package com.longxi.tianjintianbao.ui.activity.assetscheck;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponseWebPd;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.ui.activity.scan.ScanActivity2;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.utils.AESUtil;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class TestActivity3 extends BaseActivity {

    @BindView(R.id.etReceiptNumber)
    EditText etReceiptNumber;
    @BindView(R.id.btnDownload)
    Button btnDownload;
    @BindView(R.id.tvName)
    TextView tvName;

    private String searchCode = "";

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_test3;
    }

    @Override
    public void initView() {
        super.initView();
        setTvLeft("返回");
        setTitle("资产查询");
        setIvRight(R.mipmap.ic_scan);
    }

    @Override
    public void initData() {
        super.initData();
    }

    @Override
    public void initListener() {
        super.initListener();
        mIvRight.setOnClickListener(view -> scan());
        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchCode = etReceiptNumber.getText().toString().trim();
                search();
            }
        });
    }

    private void search(){
        if(TextUtils.isEmpty(searchCode)){
            MyUtils.showToast("条形码不存在");
            return;
        }

        showWaitingDialog("正在下载");

        String usernameApassword = "";
        try {
            usernameApassword = MyApplication.username + ",," + AESUtil.encrypt(MyApplication.password, "1234567890123456");
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject object = new JSONObject();
        try {
            object.put("type", "getdata");
            object.put("validate", usernameApassword);
            object.put("billtype", "card");
            object.put("billcode", searchCode);
            object.put("billdata", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().validate(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponseWebPd>(this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponseWebPd result) {
                hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }

                if(result.getData().contains("ERROR")){
                    MyUtils.showToast(result.getData());
                    return;
                }
                String[] strings = result.getData().split("\r\n");
                if(strings.length != 2){
                    return;
                }
                String[] title = strings[0].split(",");
                String[] value = strings[1].split(",");
                String name = "";
                for (int i = 0; i < title.length; i++) {
                    name += title[i] + ":" + value[i] + "\n";
                }
                tvName.setText(name);

            }
        });
    }

    public void scan() {
        AndPermission.with(this)
        .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
        .onGranted(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                Intent intent = new Intent(TestActivity3.this, ScanActivity2.class);
                startActivityForResult(intent, AppConst.IntentRequstCode.REQUEST_CODE_SCAN);
            }
        })
        .onDenied(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                startActivity(intent);

                MyUtils.showToast("没有权限无法扫描呦");
            }
        }).start();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case AppConst.IntentRequstCode.REQUEST_CODE_SCAN:
                if (data != null) {
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        if (bundle.getInt(AppConst.RESULT_TYPE) == AppConst.RESULT_SUCCESS) {
                            String result = bundle.getString(AppConst.RESULT_STRING);
                            MyUtils.showToast(result);
                            searchCode = result;
                            search();
                        } else if (bundle.getInt(AppConst.RESULT_TYPE) == AppConst.RESULT_FAILED) {
                            MyUtils.showToast("解析二维码失败");
                        }
                    }
                }
                break;
        }
    }
}
